package repository

import (
	"rpc-service/product/datasource"
	"rpc-service/product/model"
	"sync"
)

/**
实现类
*/
type Product struct {
}

/**
单例模式
*/
var once sync.Once
var instance *Product

func GetInstance() *Product {
	once.Do(func() {
		instance = &Product{}
	})
	return instance
}

func (repo *Product) Find(id uint32) (*model.Product, error) {
	product := &model.Product{}
	product.ID = uint(id)
	if err := datasource.GetDB().First(product).Error; err != nil {
		return nil, err
	}
	return product, nil
}

func (repo *Product) Create(product *model.Product) error {
	if err := datasource.GetDB().Create(product).Error; err != nil {
		return err
	}
	return nil
}

func (repo *Product) Update(product *model.Product) (*model.Product, error) {
	if err := datasource.GetDB().Model(&product).Updates(product).Error; err != nil {
		return nil, err
	}
	return product, nil
}

func (repo *Product) Delete(product *model.Product) (*model.Product, error) {
	if product.ID > 0 {
		if err := datasource.GetDB().Delete(model.Product{}, "id=?", product.ID).Error; err != nil {
			return nil, err
		}
	}

	if len(product.Name) > 0 {
		if err := datasource.GetDB().Delete(model.Product{}, "name=?", product.Name).Error; err != nil {
			return nil, err
		}
	}
	return product, nil
}

func (repo *Product) FindListLimit(size int32) ([]model.Product, error) {
	var productList []model.Product
	if err := datasource.GetDB().Limit(size).Order("id desc").Find(&productList).Error; err != nil {
		return nil, err
	}
	return productList, nil
}

func (repo *Product) FindByField(key string, value string, fields string) (*model.Product, error) {
	if len(fields) == 0 {
		fields = "*"
	}
	product := &model.Product{}
	if err := datasource.GetDB().Select(fields).Where(key+" = ?", value).First(product).Error; err != nil {
		return nil, err
	}
	return product, nil
}
